package org.jeecg.modules.api.controller.music.user;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.vo.album.AlbumDetail;
import org.jeecg.modules.api.vo.songlist.SonglistDetailVo;
import org.jeecg.modules.api.vo.songs.SongsDetailVo;
import org.jeecg.modules.api.vo.user.UserDetailVo;
import org.jeecg.modules.api.vo.user.UserLevelVo;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.music.entity.*;
import org.jeecg.modules.music.service.*;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysLogService;
import org.jeecg.modules.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags="API-音乐系统")
@RestController
@RequestMapping("api/mus/")
public class MusUserAPIController {

    @Autowired
    private IMusUserService musUserService;

    @Autowired
    private IMusAlbumSongListService songListService;

    @Autowired
    private IMusCollectSonglistService collectSonglistService;

    @Autowired
    private IMusAlbumSongListService musAlbumSongListService;


    @Autowired
    private IMusSongService songService;

    @Autowired
    private IMusCollectSongService collectSongService;

    @Autowired
    private IMusCollectAlbumService collectAlbumService;

    @Resource
    private BaseCommonService baseCommonService;


    @Autowired
    private RedisUtil redisUtil;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
    private IMusUserService sysUserService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysLogService logService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private ISysDictService sysDictService;



    /**
     * 用户注册接口
     *
     * @param jsonObject
     * @param user
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<JSONObject> userRegister(@RequestBody JSONObject jsonObject, MusUser user) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        String nickname = jsonObject.getString("nickname");
        //未设置用户名，则用手机号作为用户名
        if (oConvertUtils.isEmpty(nickname)) {
            nickname = phone;
        }
        //未设置密码，则随机生成一个密码
        String password = jsonObject.getString("password");
        if (oConvertUtils.isEmpty(password)) {
            password = RandomUtil.randomString(8);
        }
        String email = jsonObject.getString("email");
        MusUser user1 = musUserService.getUserByNickName(nickname);
        if (user1 != null) {
            result.setMessage("改昵称已经存在");
            result.setSuccess(false);
            return result;
        }
        MusUser user2 = musUserService.getUserByPhone(phone);
        if (user2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }

        if (oConvertUtils.isNotEmpty(email)) {
            MusUser user3 = musUserService.getUserByEmail(email);
            if (user3 != null) {
                result.setMessage("邮箱已被注册");
                result.setSuccess(false);
                return result;
            }
        }
        if (null == code) {
            result.setMessage("手机验证码失效，请重新获取");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(code.toString())) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }

        try {
            user.setCreateTime(new Date());// 设置创建时间
            String salt = oConvertUtils.randomGen(8);

            user.setPassword(password);
            user.setEmail(email);
            user.setTelephone(phone);
            user.setNickname(nickname);
            user.setMember(CommonConstant.USER_MEMBER);
            user.setAvatar(CommonConstant.USER_AVATAR);
            user.setCity("33011001");
            user.setStatus(CommonConstant.USER_UNFREEZE);

            musUserService.addMusUser(user);

            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    /**
     *  校验用户账号是否唯一<br>
     *  可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @ApiOperation("校验用户账号是否唯一")
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(MusUser sysUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
            sysUser.setPassword(null);
            MusUser user = musUserService.getOne(new QueryWrapper<MusUser>(sysUser));
            if (user != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 短信登录接口
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("短信接口")
    @RequestMapping(value = "/sms", method = RequestMethod.POST)
    public Result<String> sms(@RequestBody JSONObject jsonObject) {
        Result<String> result = new Result<String>();
        String mobile = jsonObject.get("mobile").toString();
        //手机号模式 登录模式: "2"  注册模式: "1"
        String smsmode=jsonObject.get("smsmode").toString();
        log.info(mobile);
        if(oConvertUtils.isEmpty(mobile)){
            result.setMessage("手机号不允许为空！");
            result.setSuccess(false);
            return result;
        }
        Object object = redisUtil.get(mobile);
        if (object != null) {
            result.setMessage("验证码10分钟内，仍然有效！");
            result.setSuccess(false);
            return result;
        }

        //随机数
        String captcha = RandomUtil.randomNumbers(6);
        JSONObject obj = new JSONObject();
        obj.put("code", captcha);
        try {
            boolean b = false;
            //注册模板
            if (CommonConstant.SMS_TPL_TYPE_1.equals(smsmode)) {
                MusUser sysUser = sysUserService.getUserByPhone(mobile);
                if(sysUser!=null) {
                    result.error500(" 手机号已经注册，请直接登录！");
                    baseCommonService.addLog("手机号已经注册，请直接登录！", CommonConstant.LOG_TYPE_1, null);
                    return result;
                }
                b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.REGISTER_TEMPLATE_CODE);
            }else {
                //登录模式，校验用户有效性
                MusUser sysUser = sysUserService.getUserByPhone(mobile);
                result = sysUserService.checkUserIsEffective(sysUser);
                if(!result.isSuccess()) {
                    String message = result.getMessage();
                    if("该用户不存在，请注册".equals(message)){
                        result.setMessage("该用户不存在或未绑定手机号");
                        result.error500("该用户不存在或未绑定手机号");
                    }
                    return result;
                }

                /**
                 * smsmode 短信模板方式  0 .登录模板、1.注册模板、2.忘记密码模板
                 */
                if (CommonConstant.SMS_TPL_TYPE_0.equals(smsmode)) {
                    //登录模板
                    b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.LOGIN_TEMPLATE_CODE);
                } else if(CommonConstant.SMS_TPL_TYPE_2.equals(smsmode)) {
                    //忘记密码模板
                    b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE);
                }
            }

            if (b == false) {
                result.setMessage("短信验证码发送失败,请稍后重试");
                result.setSuccess(false);
                return result;
            }
            //验证码10分钟内有效
            redisUtil.set(mobile, captcha, 600);
            //update-begin--Author:scott  Date:20190812 for：issues#391
            //result.setResult(captcha);
            //update-end--Author:scott  Date:20190812 for：issues#391
            result.setSuccess(true);

        } catch (ClientException e) {
            e.printStackTrace();
            result.error500(" 短信接口未配置，请联系管理员！");
            return result;
        }
        return result;
    }

    @ApiOperation("用户详情")
    @RequestMapping(value = "/user/detail", method = RequestMethod.POST)
    public Result reqDetail(@RequestParam(name = "uid",required = true) String uid){
        Map<String,Object> map = new HashMap<>();
        UserDetailVo user = musUserService.reqDetail(uid);
        if (user!=null){
            map.put("profile",user);
            return Result.ok(map);
        }
        return Result.error("用户不存在");
    }

    @ApiOperation("获取用户等级")
    @RequestMapping(value = "/user/level", method = RequestMethod.GET)
    public Result reqLevel(@RequestParam(name = "cookie",required = true) String cookie){

        Map<String,Object> mp = new HashMap<>();
        UserLevelVo data = musUserService.queryLevel(cookie);
        if (data!=null){
            mp.put("data",data);
            return Result.ok(mp);
        }
        return Result.error("查询失败！");
    }

    @ApiOperation("收藏/取消收藏歌单")
    @RequestMapping(value = "/playlist/subscribe", method = RequestMethod.POST)
    public Result reqSubSongList(@RequestParam(name = "t") Integer t,@RequestParam("songlistId") String songlistId,@RequestParam(name = "userId") String userId){
        Map<String,Object> map = new HashMap<>();
        MusUser user = musUserService.getById(userId);
        MusAlbumSong songlist = songListService.getById(songlistId);
        if (user==null||songlist==null){
            return Result.error(401,"操作失败！");
        }else {
            MusCollectSonglist collect = new MusCollectSonglist();
            collect.setCreateTime(new Date());
            collect.setUserId(user.getId());
            collect.setUsername(user.getNickname());
            collect.setSonglistId(songlist.getId());
            collect.setSonglistName(songlist.getListname());
            //收藏
            if (t==1){
                collectSonglistService.save(collect);
                return Result.ok("收藏成功");
            }
            else if (t==2){
                collectSonglistService.deleteCollect(user.getId(),songlist.getId());
                return Result.ok("取消收藏成功！");
            }
            return Result.error(505,"系统异常");
        }
    }

    @ApiOperation("获取用户歌单")
    @RequestMapping(value = "/user/playlist", method = RequestMethod.GET)
    public Result getUserSonglist(@RequestParam(name = "uid",required = true) String uid){
        Map<String, Object> map = new HashMap<>();
        List<SonglistDetailVo> playlists = musAlbumSongListService.getUserSonglist(uid);
        List<SonglistDetailVo> mylist = musAlbumSongListService.getUserMake(uid);
        map.put("playlists",playlists);
        map.put("mylist",mylist);
        map.put("total",playlists.size());
        return Result.ok(map);
    }

    @ApiOperation("判断用户是否收藏此歌单")
    @RequestMapping(value = "/songlist/iscollect", method = RequestMethod.GET)
    public Result isCollectSonglist(@RequestParam(name = "userId",required = true) String userId,@RequestParam(name = "songlistId",required = true) String songlistId){
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<MusCollectSonglist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("songlist_id",songlistId);

        List<MusCollectSonglist> list = collectSonglistService.list(queryWrapper);
        if (list.size()>0){
            map.put("isSub",true);
        }else {
            map.put("isSub",false);
        }
        return Result.ok(map);
    }


    @ApiOperation("判断用户是否收藏此歌曲")
    @RequestMapping(value = "/song/iscollect",method = RequestMethod.GET)
    public Result isCollectSong(@RequestParam(name = "userId",required = true) String userId,@RequestParam(name = "songId",required = true) String songId){
        Map<String, Object> mp = new HashMap<>();

        QueryWrapper<MusCollectSong> wq = new QueryWrapper<>();
        wq.eq("user_id",userId).eq("song_id",songId);

        List<MusCollectSong> list = collectSongService.list(wq);

        if (list.size()>0){
            mp.put("isCollect",true);
        }
        else {
            mp.put("isCollect",false);
        }
        return Result.ok(mp);
    }

    @ApiOperation("收藏/取消收藏歌曲")
    @RequestMapping(value = "/song/subscribe", method = RequestMethod.POST)
    public Result reqCollectSong(@RequestParam(name = "t") Integer t,@RequestParam("songId") String songId,@RequestParam(name = "userId") String userId){
        Map<String,Object> map = new HashMap<>();
        MusUser user = musUserService.getById(userId);
        MusSong song = songService.getById(songId);

        if (user==null||song==null){
            return Result.error(401,"操作失败！");
        }else{
            MusCollectSong collect = new MusCollectSong();
            collect.setCreateTime(new Date());
            collect.setSongId(song.getId());
            collect.setSongName(song.getSongName());
            collect.setUserId(user.getId());
            collect.setUsername(user.getNickname());
            //收藏
            if (t==1){
                collectSongService.save(collect);
                return Result.ok("收藏成功");
            }
            else if (t==2){
                collectSongService.deleteCollect(user.getId(),song.getId());
                return Result.ok("取消收藏成功！");
            }
            return Result.error(505,"系统异常");
        }
    }

    @ApiOperation("获取用户收藏的歌曲")
    @RequestMapping(value = "/user/collect/songs", method = RequestMethod.GET)
    public Result getUserSongs(@RequestParam(name = "uid",required = true) String uid){
        Map<String, Object> resultMap = new HashMap<>();
        List<SongsDetailVo> songs = songService.querySongsByUserId(uid);
        resultMap.put("usersongs",songs);
        resultMap.put("total",songs.size());
        return Result.ok(resultMap);
    }

    @ApiOperation("判断用户是否收藏此专辑")
    @RequestMapping(value = "/album/iscollect",method = RequestMethod.GET)
    public Result isCollectAlbum(@RequestParam(name = "userId",required = true) String userId,@RequestParam(name = "albumId",required = true) String albumId){
        Map<String,Object> mp = new HashMap<>();
        QueryWrapper<MusCollectAlbum> wq = new QueryWrapper<>();
        wq.eq("user_id",userId).eq("album_id",albumId);
        List<MusCollectAlbum> list = collectAlbumService.list(wq);
        if (list.size()>0){
            mp.put("isSub",true);
        }
        else {
            mp.put("isSub",false);
        }
        return Result.ok(mp);
    }

    @ApiOperation("收藏/取消收藏专辑")
    @RequestMapping(value = "/album/subscribe", method = RequestMethod.POST)
    public Result reqCollectAlbum(@RequestParam(name = "t") Integer t,@RequestParam("albumId") String albumId,@RequestParam(name = "userId") String userId){
        Map<String,Object> map = new HashMap<>();
        MusUser user = musUserService.getById(userId);
        MusAlbumSong album = musAlbumSongListService.getById(albumId);

        if (user==null||album==null){
            return Result.error(401,"操作失败！");
        }else{
            MusCollectAlbum collect = new MusCollectAlbum();
            collect.setCreateTime(new Date());
            collect.setAlbumId(album.getId());
            collect.setAlbumName(album.getListname());
            collect.setUserId(user.getId());
            collect.setUsername(user.getNickname());
            //收藏
            if (t==1){
                collectAlbumService.save(collect);
                return Result.ok("收藏成功");
            }
            else if (t==2){
                collectAlbumService.deleteCollect(user.getId(),album.getId());
                return Result.ok("取消收藏成功！");
            }
            return Result.error(505,"系统异常");
        }
    }

    @ApiOperation("获取用户收藏的歌曲")
    @RequestMapping(value = "/user/collect/albums", method = RequestMethod.GET)
    public Result getUserAlbums(@RequestParam(name = "uid",required = true) String uid){
        Map<String, Object> map = new HashMap<>();
        List<AlbumDetail> albums = musAlbumSongListService.queryAlbumsByUser(uid);
        map.put("useralbums",albums);
        map.put("total",albums.size());
        return Result.ok(map);
    }

    @ApiOperation("查询用户详情")
    @RequestMapping(value = "/user/detail", method = RequestMethod.GET)
    public Result queryPerson(@RequestParam(name = "uid",required = true)String uid){
        Map<String,Object> map = new HashMap<>();
        MusUser user = musUserService.getById(uid);
        if (user!=null){
            map.put("user",user);
            return Result.ok(map);
        }
        return Result.error("查询失败");
    }


    @ApiOperation("用户修改个人信息")
    @RequestMapping(value = "/user/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<MusUser> updateUserBaseInfo(@RequestBody JSONObject jsonObject){
        Result<MusUser> result = new Result<MusUser>();
        try {
            MusUser user = musUserService.getById(jsonObject.getString("id"));
            baseCommonService.addLog("编辑用户，id： " +jsonObject.getString("id") , CommonConstant.LOG_TYPE_2, 2);
            if(user==null) {
                result.error500("未找到对应实体");
            }else {
                MusUser musUser = JSON.parseObject(jsonObject.toJSONString(), MusUser.class);
                musUser.setUpdateTime(new Date());
                musUserService.editUser(musUser);
                result.setCode(200);
                result.success("修改成功!");
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @ApiOperation("用户修改个人信息")
    @RequestMapping(value = "/user/changepassword", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result changePassword(@RequestParam(name = "uid",required = true)String uid,@RequestParam(name = "oldpassword",required = true)String oldpassword,@RequestParam(name = "password",required = true)String password){
        QueryWrapper<MusUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",uid).eq("password",oldpassword);
        MusUser user = musUserService.getOne(queryWrapper);
        if (user==null){
            return Result.error(201,"密码错误");
        }else {
            musUserService.changePassword(uid,password);
            return Result.ok();
        }
    }


}
